import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
const computedBehavior = require('miniprogram-computed').behavior
import {
  // ajaxGetCountriesList,
  ajaxRegisterUser,
  ajaxGetUserSourceList,
  ajaxSendMessage, ajaxQuickRegister
} from '../../../api/registerLogin'
import {
  pageLanguage
} from '../../../language/registerLogin/index'
const app = getApp()
// 检查是否可提交定时器
let checkTime = null,
  // 验证码倒计时定时器
  codeTime = null,
  // 默认表单
  defaultFormData = {
    surnames: '',
    name: '',
    sex: 2,
    countries: '中国',
    birthday: '',
    sourceId: '',
    tel: '',
    msgCode: ''
  };

Page({
  behaviors: [computedBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    // 目前登录状态
    userLoginState: false,
    // 表单数据
    formData: JSON.parse(JSON.stringify(defaultFormData)),
    // 验证码倒计时
    codeNum: 0,
    // 性别选项
    sexOptions: [],
    // 客户来源
    sourceOptions: [],
    // 同意协议
    isAgreement: false,
    // 是否能提交
    isSubmit: false,
    // 当前语言
    currentLanguage: app.globalData.language,
    // 页面国际化数据
    languageData: JSON.parse(JSON.stringify(pageLanguage[app.globalData.language].formPage))
  },
  watch: {
    'formData.**,isAgreement': function (formData, isAgreement) {
      if (checkTime) {
        clearTimeout(checkTime)
      }
      checkTime = setTimeout(() => {
        let {
          result
        } = this.isCheck();
        this.setData({
          isSubmit: result
        })
      }, 100)
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    this.setData({
      sexOptions: [{
          name: pageLanguage[app.globalData.language].formPage.boy,
          value: '2'
        },
        {
          name: pageLanguage[app.globalData.language].formPage.girl,
          value: '1'
        }
      ]
    })

    //loading
    Toast.loading({
      message: pageLanguage[app.globalData.language].formPageToast.loading,
      forbidClick: true,
      duration: 0
    });

    try {
      let {
        data
      } = await ajaxGetUserSourceList({
        ifShowRegister: 'Y'
      })
      data = (data || []).map(item => {
        return Object.assign({}, item, {
          name: item.sourceDesc,
          value: item.sourceId
        })
      })
      this.setData({
        'sourceOptions': data
      })
      await app.myNextTick()
      Toast.clear();
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || pageLanguage[app.globalData.language].formPageToast.error)
    }

    // let {
    //   data
    // } = await ajaxGetCountriesList();
    // data = (data || []).slice(0, 10).map(item => {
    //   return {
    //     name: item.name,
    //     value: item.name
    //   }
    // })
    // this.setData({
    //   countriesOptions: data
    // })
  },
  // 切换中英文
  switchLanguage(e) {
    let {
      name
    } = e.currentTarget.dataset;
    app.globalData.language = name;
    this.updateLanguage();
  },
  // 更新语言
  updateLanguage() {
    this.setData({
      currentLanguage: app.globalData.language,
      languageData: JSON.parse(JSON.stringify(pageLanguage[app.globalData.language].formPage)),
      sexOptions: [{
          name: pageLanguage[app.globalData.language].formPage.boy,
          value: '2'
        },
        {
          name: pageLanguage[app.globalData.language].formPage.girl,
          value: '1'
        }
      ]
    })
  },
  // 协议change
  agreementChange(e) {
    this.setData({
      isAgreement: e.detail
    })
  },
  // form-item数据change
  updateValue(e) {
    let name = e.currentTarget.dataset.inputName,
      value = e.detail || '';
    this.setData({
      [name]: value
    });
  },
  // 发送验证码
  async sendCode() {
    if (codeTime) {
      return
    }
    if (!/^\d{11}$/g.test(this.data.formData.tel)) {
      Toast(pageLanguage[app.globalData.language].formPageToast.checkTel)
      return;
    }
    //loading
    Toast.loading({
      message: pageLanguage[app.globalData.language].formPageToast.loadingSend,
      forbidClick: true,
      duration: 0
    });

    try {
      await ajaxSendMessage({
        tel: this.data.formData.tel,
        //  注册1 登录2
        smsType: 1
      })
      this.setData({
        codeNum: 59
      })
      codeTime = setInterval(() => {
        let newCodeNum = this.data.codeNum - 1;
        if (newCodeNum <= 0) {
          clearInterval(codeTime)
          codeTime = null
        }
        this.setData({
          codeNum: newCodeNum
        })
      }, 1000)
      await app.myNextTick()
      Toast.clear();
      Toast(pageLanguage[app.globalData.language].formPageToast.codeSendOk)
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || pageLanguage[app.globalData.language].formPageToast.error)
    }
  },
  // 校验数据
  isCheck(isShowMsg = false) {
    let {
      formData,
      isAgreement
    } = this.data;
    if (!formData.surnames) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkSurname
      };
    }
    if (!formData.name) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkName
      };
    }
    if (!formData.birthday) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkBirthDate
      };
    }
    // if (!formData.sourceId) {
    //   return {
    //     result: false,
    //     msg: pageLanguage[app.globalData.language].formPageToast.checkCustomerSource
    //   };
    // }
    if (!/^\d{11}$/g.test(formData.tel)) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkTel
      };
    }
    // if (!formData.msgCode) {
    //   return {
    //     result: false,
    //     msg: pageLanguage[app.globalData.language].formPageToast.checkCode
    //   };
    // }
    if (!isAgreement) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkAgreement
      };
    }
    return {
      result: true,
      msg: 'ok'
    };
  },
  // 提交
  async submit(e) {
    let {
      result,
      msg
    } = this.isCheck(true)
    if (!result) {
      Toast(msg)
      return;
    }
    let {
      login
    } = e.currentTarget.dataset;

    //loading
    Toast.loading({
      message: pageLanguage[app.globalData.language].formPageToast.processing,
      forbidClick: true,
      duration: 0
    });

    try {
      // 获取微信用户的openIdCode
      let openIdCode = await app.getOpenIdCode();
      // 注册
      let {
        data
      } = await ajaxRegisterUser(Object.assign({}, this.data.formData, {
        wxCode: openIdCode,
        wxAppId: app.globalData.config.server.APPID,
      }))
      await app.myNextTick()
      Toast.clear();
      // 提交并登录 && 目前不是登录状态
      if (login && !app.globalData.userLoginState) {
        // 登录
        await app.initLogin({
          // surnames: this.data.formData.surnames,
          // name: this.data.formData.name,
          k1UserId: data.userId,
          tel: this.data.formData.tel,
          msgCode: '990105',
        });
        // 清空验证码
        this.setData({
          'formData.msgCode': ''
        })
        // 登录成功跳转到首页
        app.commonToPage('/pages/home/index', 'switchTab', {}, () => {
          wx.showToast({
            title: pageLanguage[app.globalData.language].formPageToast.loginOk,
            icon: 'success',
            duration: 2000
          })
        })
      } else {
        // 清除表单数据
        this.setData({
          formData: JSON.parse(JSON.stringify(defaultFormData))
        })
        Toast.success(pageLanguage[app.globalData.language].formPageToast.registerOk);
      }
    } catch (err) {
      // 清空验证码
      this.setData({
        'formData.msgCode': ''
      })
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || pageLanguage[app.globalData.language].formPageToast.error)
    }
  },
  // 去注册协议页面
  goAgreements() {
    app.commonNavigateTo('/pages/agreements/register/index')
  },


  async getPhoneNumber(e){
    console.log(e)
    console.log(e.detail.code)  // 动态令牌
    if (!e.detail.code) {
      //Toast.clear();
      Toast('获取手机号码失败');
      return;
    }


    Toast.loading({
      message: pageLanguage[app.globalData.language].formPageToast.processing,
      forbidClick: true,
      duration: 0
    });

    try {
      let params = {code:e.detail.code,appId:app.globalData.config.server.APPID};
      // 注册
      let {
        data
      } = await ajaxQuickRegister(params);

      await app.myNextTick()
      Toast.clear();

      if (!app.globalData.userLoginState) {
          // 登录
          await app.initLogin({
            // surnames: this.data.formData.surnames,
            // name: this.data.formData.name,
            k1UserId: data.userId,
            //tel: this.data.formData.tel,
            //msgCode: '990105',
          });

          // 登录成功跳转到首页
          app.commonToPage('/pages/home/index', 'switchTab', {}, () => {
            wx.showToast({
              title: pageLanguage[app.globalData.language].formPageToast.loginOk,
              icon: 'success',
              duration: 2000
            })
          })

      } else {
        // 清除表单数据
        this.setData({
          formData: JSON.parse(JSON.stringify(defaultFormData))
        })
        Toast.success(pageLanguage[app.globalData.language].formPageToast.registerOk);
      }



    } catch (err) {
      // 清空验证码
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || pageLanguage[app.globalData.language].formPageToast.error)
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userLoginState: app.globalData.userLoginState
    })
    if (this.data.currentLanguage != app.globalData.language) {
      this.updateLanguage();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (checkTime) {
      clearTimeout(checkTime)
      checkTime = null;
    }
    if (codeTime) {
      clearInterval(codeTime)
      codeTime = null
    }
  }
})